import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';
import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog';

const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    username: "",
    password: "",
    nickname: "",
    phone: "",
    login: false,
    registy: false,
    user: null,
    errorUsername: "",
    errorPassword: "",
    errorNickname: "",
    errorPhone: "",
    studyTime: 0
  },

  toLearnRecord() {
    let {
      user
    } = this.data;
    wx.navigateTo({
      url: `/pages/learnRecord/index?id=${user.id}`,
    });
  },

  onFieldFocus(data) {
    let {
      label
    } = data.currentTarget.dataset;
    var errorMsg = "";
    if (label == "用户名") {
      this.setData({
        errorUsername: errorMsg
      });
    } else if (label == "密码") {
      this.setData({
        errorPassword: errorMsg
      });
    } else if (label == "昵称") {
      this.setData({
        errorNickname: errorMsg
      });
    } else if (label == "手机号") {
      this.setData({
        errorPhone: errorMsg
      });
    }
  },

  onFieldBlur(data) {
    let {
      label
    } = data.currentTarget.dataset;
    // console.log(label);
    var errorMsg = "";
    if (label == "用户名" && this.data.username == "") {
      errorMsg = "用户名不能为空"
      this.setData({
        errorUsername: errorMsg
      });
    } else if (label == "密码" && this.data.password == "") {
      errorMsg = "密码"
      this.setData({
        errorPassword: errorMsg
      });
    } else if (label == "昵称" && this.data.nickname == "") {
      errorMsg = "手机号"
      this.setData({
        errorNickname: errorMsg
      });
    } else if (label == "手机号" && this.data.phone == "") {
      errorMsg = "手机号不能为空"
      this.setData({
        errorPhone: errorMsg
      });
    }
  },

  registryToJava() {
    let userName = this.data.username;
    let {
      password,
      nickname,
      phone
    } = this.data;
    var that = this;
    var url = `${app.globalData.baseURL}/api/member/member/registry`;
    wx.request({
      url,
      method: "POST",
      data: {
        levelId: 1,
        userName,
        password,
        nickname,
        phone
      },
      success(res) {
        // console.log(res);
        let {
          user
        } = res.data;
        if (user == null) {
          Toast('注册失败，用户名或电话不能重复');
          return;
        }
        Toast('注册成功，即将为你登录跳转');
        setTimeout(() => {
          // 将用户数据加载到本地storage
          wx.setStorage({
            key: "user",
            data: user
          })
          that.setData({
            user,
            login: false,
            registy: false
          })
        }, 800);
      }
    })

  },

  loginToJava() {
    let userName = this.data.username;
    let password = this.data.password;
    if (userName == null || userName == '' || password == null || password == '') {
      Toast('用户名或密码不能为空');
      return;
    }
    // 登录校验
    var that = this;
    var url = `${app.globalData.baseURL}/api/member/member/login`;
    wx.request({
      url,
      method: "POST",
      data: {
        userName,
        password
      },
      success(res) {
        // console.log(res.data.user);
        let {
          user
        } = res.data;
        if (user == null) {
          Toast('用户名或密码错误');
        } else {
          that.setData({
            username: "",
            password: ""
          })
          Toast('登录成功');
          setTimeout(() => {
            // 将用户数据加载到本地storage
            wx.setStorage({
              key: "user",
              data: user
            })
            that.setData({
              user
            });
          }, 800);
        }
      }
    })
  },

  toLogin() {
    this.setData({
      registy: false,
      login: true,
      username: "",
      password: ""
    })
  },

  toRegistry() {
    // console.log("111")
    this.setData({
      registy: true,
      login: false,
      username: "",
      password: ""
    })
  },

  onClickIconNickname(data) {
    Toast('昵称在你登录后显示');
  },

  onClickIconUsername(data) {
    Toast('用户名是你登录时的名字');
  },

  // 监听 dialog 框关闭
  onClose(data) {
    // console.log(data);
  },

  /**
   * 检测登录
   * 
   */
  onLoad: function (options) {
    // 0.如果权限不足跳转来，则直接进去登录页
    let {
      login
    } = options;
    if (login != null && login != undefined) {
      this.setData({
        login
      })
      return;
    }
    var that = this;
    // 1.查询是否登录
    // 1.1.如果本地含有用户信息，自动登录
    var user = null;
    try {
      user = wx.getStorageSync('user');
      // console.log("user = " + user);
    } catch (e) {
      user = null;
    }
    if (user == null || user == "") {
      // 2.提示
      Dialog.alert({
        title: '当前未登录',
        message: '此操作需要登录',
        theme: 'round-button',
      }).then(() => {
        // 3.前往登录页，此处将 login 状态改为 true
        that.setData({
          login: true
        });
      });
    } else {
      this.setData({
        user
      })
    }

    // *.
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  // 设置自定义tabbar，active显示属性
  onShow() {
    // 检查用户是否登录
    var user = null;
    try {
      user = wx.getStorageSync('user');
    } catch (error) {
      user = null;
    }
    if (user == null || user == "") {
      // console.log("user is null");
      this.setData({
        studyTime: 0,
        user,
        login: true,
        registy: false
      })
    }

    // console.log("主页tab");
    if (typeof this.getTabBar === 'function' &&
      this.getTabBar()) {
      this.getTabBar().setData({
        active: 3
      })
    }

    // 每隔 30 s获取一次今日学习时长
    var that = this;
    setInterval(() => {
      if (that.data.user != null && that.data.user != '') {
        wx.request({
          url: `${app.globalData.baseURL}/api/study/studytime/studyTimeByUserId?memberId=${that.data.user.id}`,
          success(res) {
            // console.log(res);
            let {
              studyTime
            } = res.data;
            // console.log(studyTime);
            that.setData({
              studyTime
            })
          }
        })
      }
    }, 30000);
  }
})